/*
 *
 *  Copyright 2017-2019 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */
package com.jingtai.platform.config;
//package springfox.springconfig;

import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jingtai.validate.swagger.CApiModelProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.service.AllowableListValues;
import springfox.documentation.service.AllowableRangeValues;
import springfox.documentation.service.AllowableValues;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.google.common.collect.Lists.newArrayList;
import static org.springframework.util.StringUtils.hasText;
import static springfox.documentation.schema.Annotations.findPropertyAnnotation;

/**
 * @author zhengchao
 * @date 2020年4月6日
 *
 */
@Component("swaggerCApiModelPropertyDescriptionReader")
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class CApiModelPropertyReader implements ModelPropertyBuilderPlugin {
	private final DescriptionResolver descriptions;

	@Autowired
	public CApiModelPropertyReader(DescriptionResolver descriptions) {
		this.descriptions = descriptions;
	}

	@Override
	public void apply(ModelPropertyContext context) {

		Optional<CApiModelProperty> annotation = Optional.absent();

		if (context.getAnnotatedElement().isPresent()) {
			annotation = annotation.or(findApiModePropertyAnnotation(context.getAnnotatedElement().get()));
		}
		if (context.getBeanPropertyDefinition().isPresent()) {
			annotation = annotation
					.or(findPropertyAnnotation(context.getBeanPropertyDefinition().get(), CApiModelProperty.class));
		}

		// CApiModelProperty annotationx = annotation.get();
		StringBuffer description = new StringBuffer();
		description.append(annotation.transform(toDescription(descriptions)).orNull());
		// description.append(emptyToNull(descriptions.resolve(annotation.comment())));
		List<String> defCheckList = new ArrayList<>();
		if (annotation.transform(toIsRequired()).or(false)) {
			defCheckList.add("必填");
		} else {
			defCheckList.add("选填");
		}
		if (annotation.transform(notEmpty()).or(false)) {
			defCheckList.add("不允许为空");
		}
		if (annotation.transform(email()).or(false)) {
			defCheckList.add("邮箱格式");
		}
		if (annotation.transform(phone()).or(false)) {
			defCheckList.add("手机号码格式");
		}
		if (annotation.transform(cIntMax()).or(Integer.MAX_VALUE) != Integer.MAX_VALUE) {
			defCheckList.add("整数最大值:" + annotation.transform(cIntMax()).or(Integer.MAX_VALUE));
		}
		if (annotation.transform(cIntMin()).or(Integer.MIN_VALUE) != Integer.MIN_VALUE) {
			defCheckList.add("整数最小值:" + annotation.transform(cIntMin()).or(Integer.MIN_VALUE));
		}
		if (annotation.transform(cStrMaxLen()).or(Integer.MAX_VALUE) != Integer.MAX_VALUE) {
			defCheckList.add("字符串最长:" + annotation.transform(cStrMaxLen()).or(Integer.MAX_VALUE));
		}
		if (annotation.transform(cStrMinLen()).or(0) != Integer.MIN_VALUE) {
			defCheckList.add("字符串最短:" + annotation.transform(cStrMinLen()).or(0));
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(annotation.transform(regex()).or(""))) {
			defCheckList.add("正则要求:" + annotation.transform(regex()).or(""));
		}
		description.append("  " + defCheckList.toString());

		if (annotation.isPresent()) {
			context.getBuilder().allowableValues(annotation.transform(toAllowableValues()).orNull())
					.required(annotation.transform(toIsRequired()).or(false))
					.readOnly(annotation.transform(toIsReadOnly()).or(false)).description(description.toString())
//					.description(annotation.transform(toDescription(descriptions)).orNull())
					.isHidden(annotation.transform(toHidden()).or(false))
					.type(annotation.transform(toType(context.getResolver())).orNull())
					.position(annotation.transform(toPosition()).or(0))
					.example(annotation.transform(toExample()).orNull());
		}
	}

	@Override
	public boolean supports(DocumentationType delimiter) {
		return true;
	}

	private static final Logger LOGGER = LoggerFactory.getLogger(CApiModelProperty.class);
	private static final Pattern RANGE_PATTERN = Pattern.compile("range([\\[(])(.*),(.*)([])])$");

	static Function<CApiModelProperty, AllowableValues> toAllowableValues() {
		return new Function<CApiModelProperty, AllowableValues>() {
			@Override
			public AllowableValues apply(CApiModelProperty annotation) {
				return allowableValueFromString(annotation.allowableValues());
			}
		};
	}

	public static AllowableValues allowableValueFromString(String allowableValueString) {
		AllowableValues allowableValues = new AllowableListValues(Lists.<String>newArrayList(), "LIST");
		String trimmed = allowableValueString.trim();
		Matcher matcher = RANGE_PATTERN.matcher(trimmed.replaceAll(" ", ""));
		if (matcher.matches()) {
			if (matcher.groupCount() != 4) {
				LOGGER.warn("Unable to parse range specified {} correctly", trimmed);
			} else {
				allowableValues = new AllowableRangeValues(
						matcher.group(2).contains("infinity") ? null : matcher.group(2), matcher.group(1).equals("("),
						matcher.group(3).contains("infinity") ? null : matcher.group(3), matcher.group(4).equals(")"));
			}
		} else if (trimmed.contains(",")) {
			Iterable<String> split = Splitter.on(',').trimResults().omitEmptyStrings().split(trimmed);
			allowableValues = new AllowableListValues(newArrayList(split), "LIST");
		} else if (hasText(trimmed)) {
			List<String> singleVal = Collections.singletonList(trimmed);
			allowableValues = new AllowableListValues(singleVal, "LIST");
		}
		return allowableValues;
	}

	static Function<CApiModelProperty, Integer> cStrMaxLen() {
		return new Function<CApiModelProperty, Integer>() {
			@Override
			public Integer apply(CApiModelProperty annotation) {
				return annotation.cStrMaxLen();
			}
		};
	}

	static Function<CApiModelProperty, String> regex() {
		return new Function<CApiModelProperty, String>() {
			@Override
			public String apply(CApiModelProperty annotation) {
				return annotation.cregexp();
			}
		};
	}

	static Function<CApiModelProperty, Integer> cStrMinLen() {
		return new Function<CApiModelProperty, Integer>() {
			@Override
			public Integer apply(CApiModelProperty annotation) {
				return annotation.cStrMinLen();
			}
		};
	}

	static Function<CApiModelProperty, Integer> cIntMin() {
		return new Function<CApiModelProperty, Integer>() {
			@Override
			public Integer apply(CApiModelProperty annotation) {
				return annotation.cIntMin();
			}
		};
	}

	static Function<CApiModelProperty, Integer> cIntMax() {
		return new Function<CApiModelProperty, Integer>() {
			@Override
			public Integer apply(CApiModelProperty annotation) {
				return annotation.cIntMax();
			}
		};
	}

	static Function<CApiModelProperty, Boolean> email() {
		return new Function<CApiModelProperty, Boolean>() {
			@Override
			public Boolean apply(CApiModelProperty annotation) {
				return annotation.cEmail();
			}
		};
	}

	static Function<CApiModelProperty, Boolean> phone() {
		return new Function<CApiModelProperty, Boolean>() {
			@Override
			public Boolean apply(CApiModelProperty annotation) {
				return annotation.cPhone();
			}
		};
	}

	static Function<CApiModelProperty, Boolean> notEmpty() {
		return new Function<CApiModelProperty, Boolean>() {
			@Override
			public Boolean apply(CApiModelProperty annotation) {
				return annotation.cNotEmpty();
			}
		};
	}

	static Function<CApiModelProperty, Boolean> toIsRequired() {
		return new Function<CApiModelProperty, Boolean>() {
			@Override
			public Boolean apply(CApiModelProperty annotation) {
				return annotation.required();
			}
		};
	}

	static Function<CApiModelProperty, Integer> toPosition() {
		return new Function<CApiModelProperty, Integer>() {
			@Override
			public Integer apply(CApiModelProperty annotation) {
				return annotation.position();
			}
		};
	}

	static Function<CApiModelProperty, Boolean> toIsReadOnly() {
		return new Function<CApiModelProperty, Boolean>() {
			@Override
			public Boolean apply(CApiModelProperty annotation) {
				return annotation.readOnly();
			}
		};
	}

	static Function<CApiModelProperty, Boolean> toAllowEmptyValue() {
		return new Function<CApiModelProperty, Boolean>() {
			@Override
			public Boolean apply(CApiModelProperty annotation) {
				return annotation.allowEmptyValue();
			}
		};
	}

	static Function<CApiModelProperty, String> toDescription(final DescriptionResolver descriptions) {

		return new Function<CApiModelProperty, String>() {
			@Override
			public String apply(CApiModelProperty annotation) {
				String description = "";
				if (!Strings.isNullOrEmpty(annotation.value())) {
					description = annotation.value();
				} else if (!Strings.isNullOrEmpty(annotation.notes())) {
					description = annotation.notes();
				}
				return descriptions.resolve(description);
			}
		};
	}

	static Function<CApiModelProperty, ResolvedType> toType(final TypeResolver resolver) {
		return new Function<CApiModelProperty, ResolvedType>() {
			@Override
			public ResolvedType apply(CApiModelProperty annotation) {
				try {
					return resolver.resolve(Class.forName(annotation.dataType()));
				} catch (ClassNotFoundException e) {
					return resolver.resolve(Object.class);
				}
			}
		};
	}

	public static Optional<CApiModelProperty> findApiModePropertyAnnotation(AnnotatedElement annotated) {
		Optional<CApiModelProperty> annotation = Optional.absent();

		if (annotated instanceof Method) {
			// If the annotated element is a method we can use this information to check
			// superclasses as well
			annotation = Optional
					.fromNullable(AnnotationUtils.findAnnotation(((Method) annotated), CApiModelProperty.class));
		}

		return annotation.or(Optional.fromNullable(AnnotationUtils.getAnnotation(annotated, CApiModelProperty.class)));
	}

	static Function<CApiModelProperty, Boolean> toHidden() {
		return new Function<CApiModelProperty, Boolean>() {
			@Override
			public Boolean apply(CApiModelProperty annotation) {
				return annotation.hidden();
			}
		};
	}

	static Function<CApiModelProperty, String> toExample() {
		return new Function<CApiModelProperty, String>() {
			@Override
			public String apply(CApiModelProperty annotation) {
				String example = "";
				if (!Strings.isNullOrEmpty(annotation.example())) {
					example = annotation.example();
				}
				return example;
			}
		};
	}
}
